package br.com.danilloguimaraes.crudveiculo.daos;

import br.com.danilloguimaraes.utils.Utils;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;

/**
 *
 * @author danillo
 */
public class Dao<E> {
    
    private static EntityManager em = null;
    private static Dao dao = null;
    
    private Dao(){
        
    }
    
    public static Dao getDao(){
        if(Utils.isNull(dao)){
            dao = new Dao();
            em = Persistence.createEntityManagerFactory("crudVeiculo.pu").
                    createEntityManager();
        }
        return dao;
    }
    
    public void insere(E entity){
        em.getTransaction().begin();
        em.persist(entity);
        em.getTransaction().commit();
    }
    
    public void atualiza(E entity){
        em.getTransaction().begin();
        em.merge(entity);
        em.getTransaction().commit();
    }

    public List<E> todos(Class klass){
        StringBuilder sb = new StringBuilder("select v from ").
                append(klass.getSimpleName()).append(" v");
        return em.createQuery(sb.toString(), klass).getResultList();
    }
    
}
